package com.mate.cloud.druid.config;

import com.mate.cloud.druid.servlet.MonitorViewServlet;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

/**
 * 微服务分布式监控
 *
 * @author cong zhi
 * @email 448341911@qq.com
 * @createDate 2023/3/6 10:00
 * @version: v1.0
 */
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(MonitorProperties.class)
public class DruidMonitorAutoConfiguration {

    @Bean
    public ServletRegistrationBean statViewServletRegistrationBean(MonitorProperties properties) {
        ServletRegistrationBean registrationBean = new ServletRegistrationBean();
        registrationBean.setServlet(new MonitorViewServlet());
        registrationBean.addUrlMappings(getUrlMappings(properties));
        if (properties.getLoginUsername() != null) {
            registrationBean.addInitParameter("loginUsername", properties.getLoginUsername());
        }
        if (properties.getLoginPassword() != null) {
            registrationBean.addInitParameter("loginPassword", properties.getLoginPassword());
        }
        return registrationBean;
    }

    private String getUrlMappings(MonitorProperties properties) {
        String urlMapping = "/druid/*";
        if(StringUtils.isEmpty(properties.getContextPath())) {
            return urlMapping;
        }

        if(!properties.getContextPath().startsWith("/") || properties.getContextPath().endsWith("/")) {
            throw new IllegalArgumentException("Druid ContextPath must start with '/' and not end with '/'");
        }
        return properties.getContextPath() + "/*";
    }
}
